<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
    class="w-full"
  >
    <el-form-item label="资源类型" prop="type">
      <el-select v-model="newFormInline.type" placeholder="请选择">
        <el-option label="普通音频文件" :value="1" />
        <el-option label="TTS" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item
      label="文件上传"
      style="margin-top: 30px; margin-bottom: 12px"
    >
      <el-upload
        ref="upload"
        class="upload-demo upload-container"
        drag
        method="post"
        action="/api/File/upload"
        accept=".mp3,.wav,.ogg,.txt"
        :on-success="handleFileSuccess"
        :before-upload="beforeFileUpload"
        :limit="1"
        :on-exceed="handleExceed"
        style="width: 100% !important; height: 180px !important"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">点击选择文件或拖拽文件到此处</div>
        <!-- <div class="el-upload__tip text-center">支持格式: MP3, WAV, OGG, TTS</div> -->
      </el-upload>
    </el-form-item>
    <el-form-item label="文件名称" prop="name">
      <el-input v-model="newFormInline.name" placeholder="请输入资源名称" />
    </el-form-item>
    <el-form-item label="文件键" prop="fileKey">
      <el-input
        v-model="newFormInline.fileKey"
        placeholder="自动生成或手动输入"
      />
    </el-form-item>
    <el-form-item label="资源编号" prop="code">
      <el-input
        v-model="newFormInline.code"
        type="number"
        placeholder="请输入资源编号"
      />
    </el-form-item>
    <el-form-item label="备注" prop="comment">
      <el-input
        v-model="newFormInline.comment"
        type="textarea"
        :maxlength="200"
        show-word-limit
        :rows="4"
        placeholder="请输入备注，最多200字"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, watch, withDefaults } from "vue";
import { FormProps, ResourceItem } from "../componentsUtils/type/resourceTypes";
import { formRules } from "../componentsUtils/rule/resourceRules";
import { ElMessage } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = files => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};
const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: 0,
    dealerId: 0,
    tenantId: 0,
    name: "",
    code: 0,
    type: 1,
    comment: "",
    fileId: 0,
    //fileName: "",
    fileSize: 0,
    fileKey: ""
  }),
  title: ""
});
const newFormInline = ref(props.formInline);
const ruleFormRef = ref();
// 监听props.form的变化，同步到localForm
watch(
  () => props.formInline,
  newValue => {
    newFormInline.value = { ...newValue };
  },
  { deep: true }
);
// 处理文件上传成功回调
const handleFileSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  // 将上传成功返回的信息赋值给对应的字段
  newFormInline.value.fileId = response.Data?.FileId || 0;
  newFormInline.value.name = response.Data?.FileName || uploadFile.name;
  newFormInline.value.fileKey = response.Data?.FileKey || "";
  newFormInline.value.fileSize = response.Data?.FileSize || 0;

  //ElMessage.success("文件上传成功");
  console.log("文件上传成功:", response);
};
// 上传前验证
const beforeFileUpload: UploadProps["beforeUpload"] = rawFile => {
  // 根据资源类型动态调整文件类型验证规则
  let validTypes = [".mp3", ".wav", ".ogg"];
  let errorMessage = "只能上传MP3、WAV或OGG格式的音频文件!";

  // 如果资源类型为TTS（值为2），则限制只能上传txt文件
  if (newFormInline.value.type === 2) {
    validTypes = [".txt"];
    errorMessage = "当资源类型为TTS时，只能上传txt格式的文件!";
  }

  const fileExtension = rawFile.name
    .toLowerCase()
    .slice(rawFile.name.lastIndexOf("."));

  if (!validTypes.includes(fileExtension)) {
    ElMessage.error(errorMessage);
    return false;
  }

  return true;
};
function getRef() {
  return ruleFormRef.value;
}
// 添加获取表单数据的方法
function getFormData() {
  return newFormInline.value;
}
defineExpose({ getRef, getFormData });
</script>
<style scoped>
/* 确保表单内容区域完全撑满 */
.el-form-item__content {
  width: 100% !important;
}

/* 主容器样式 */
.upload-container {
  display: flex !important;
  flex-direction: column !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  min-height: 100px;
  max-height: 100%;
  padding: 0 !important;
  margin: 0 !important;
  text-align: center;

  /* border: 2px dashed #dcdcdc; */
  border-radius: 6px;
  transition: all 0.3s;
}

/* 使用深度选择器强制覆盖Element Plus默认样式 */
.upload-container ::v-deep(.el-upload) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  height: 100% !important;
  padding: 0 !important;
  margin: 0 !important;
}

.upload-container ::v-deep(.el-upload--text) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  height: 100% !important;
  padding: 0 !important;
  margin: 0 !important;
}

.upload-container ::v-deep(.el-upload-dragger) {
  display: flex !important;
  flex-direction: column !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  height: 100% !important;
  min-height: 180px !important;
  padding: 40px 10px !important;
  margin: 0 !important;
}

.upload-container:hover {
  border-color: #4096ff;
}

.upload-container ::v-deep(.el-upload__text) {
  margin: 16px 0;
  color: #606266;
}

.upload-container ::v-deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
}
</style>
